export default {
  namespaced:true,
  state:()=>({
      // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
        cart: JSON.parse(uni.getStorageSync('guangtou-shop-cart')||'[]')
  }), 
  mutations:{
    addToCart(state,goods){
      const findResult=state.cart.find(item=>item.goods_id===goods.goods_id)
      if(findResult){
        findResult.goods_count++
        console.log("数量加一")
      }else{
         console.log("保存")
        state.cart.push(goods)
      }
      
      //保存到本地
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state){
      uni.setStorageSync('guangtou-shop-cart',JSON.stringify(state.cart))
    },
    updateGoodsState(state,goods){
      const findResult=state.cart.find(item=>item.goods_id===goods.goods_id)
      if(findResult){
        findResult.goods_state=goods.goods_state
        this.commit('m_cart/saveToStorage')
      }
    },
    updateGoodsCount(state,goods){
      const findResult=state.cart.find(item=>item.goods_id===goods.goods_id)
      if(findResult){
        findResult.goods_count=goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    removeGoodsById(state,goods_id){
      state.cart= state.cart.filter(item=>item.goods_id!==goods_id)
      this.commit('m_cart/saveToStorage')
    },
    updateGoodsStateAll(state,newState){
      state.cart.forEach(item=>item.goods_state=newState) 
      this.commit('m_cart/saveToStorage')
    }
  },
  getters:{
    total(state){
     return state.cart.reduce((sum,current)=>sum+=current.goods_count,0)
    },
    checkedCount(state){
      return state.cart.filter(item=>item.goods_state).reduce((sum,pre)=>sum+=pre.goods_count,0)
    },
    getGoodsAmount(state){
      return state.cart.filter(item=>item.goods_state)
                       .reduce((sum,pre)=>sum+=pre.goods_count*pre.goods_price,0)
                       .toFixed(2)
    }
  },
  
  
}